/**
 * v-auth
 * 按钮权限指令
 * 使用方式：
 * 1. 单个权限检查: v-auth="'role:add'"
 * 2. 多个权限检查(需全部满足): v-auth="['role:add', 'role:edit']"
 * 3. 多个权限检查(满足任意一个): v-auth="{ any: ['role:add', 'role:edit'] }"
 * 4. 多个权限检查(全部满足): v-auth="{ all: ['role:add', 'role:edit'] }"
 */
import { useAuthStore } from "@/stores/modules/auth";
import type { Directive, DirectiveBinding } from "vue";

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    const authStore = useAuthStore();

    // 获取用户所有权限列表（扁平化）
    const userPermissions = authStore.authButtonListFlat || [];

    // 检查权限的函数
    const checkPermission = (required: string | string[] | { any?: string[]; all?: string[] }) => {
      if (typeof required === "string") {
        // 单个权限检查
        return userPermissions.includes(required);
      } else if (Array.isArray(required)) {
        // 数组形式 - 默认需要全部满足
        return required.every(perm => userPermissions.includes(perm));
      } else if (required && typeof required === "object") {
        // 对象形式 - 支持 any 或 all 条件
        if (required.any) {
          // 任意一个权限满足即可
          return required.any.some(perm => userPermissions.includes(perm));
        } else if (required.all) {
          // 需要全部权限满足
          return required.all.every(perm => userPermissions.includes(perm));
        }
      }
      return false;
    };

    // 如果没有权限，移除元素
    if (!checkPermission(value)) {
      el.remove();
    }
  }
};

export default auth;
